<template>
  <div id="Message">

    <!-- 左侧的聊天列表以及搜索框 -->
    <div class="left">
      <!-- 搜索框和创建群聊按钮 -->
      <div class="searchBox">
        <el-input
            v-model="search"          style="width: 240px"
            size="large"
            placeholder="搜索好友/群聊"
            maxlength="13"
            :prefix-icon="Search"
            @keyup.enter="filterChats"
        />
        <el-button :icon="Plus" circle />
      </div>
      <!-- 聊天列表 -->
      <div class="chatList">
        <h3>聊天列表</h3>
        <ul class="chatList-ul">
          <li
              v-for="(item, index) in filteredChats"
              :key="index"
              @click="selectChat(item)"
              :class="{ 'selected': item === selectedChat }"
          >
            <div class="imgBox"></div>
            <div class="textBox">
              <span class="username">{{ item.username }}</span>
              <span class="msg">{{ item.lastMessage }}</span>
            </div>
            <div class="timeBox">
              <span class="time">{{ item.time }}</span>
              <div class="num">{{ item.num }}</div>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 右侧的聊天 -->
    <div class="right">
      <!-- 用户的头像和个性签名 -->
      <div class="title" v-if="selectedChat">
        <div class="imgBox"></div>
        <div class="textBox">
          <span class="username">{{ selectedChat.username }}</span>
          <span class="signature">巧者劳而智者忧，无能者无所求</span>
        </div>
      </div>
      <!-- 聊天页面 -->
      <div class="chat" v-if="selectedChat">
        <div class="message-container" ref="messageContainer">
          <div
              v-for="(msg, index) in selectedChat.messages"
              :key="index"
              :class="['message', msg.isSent ? 'message-sent' : 'message-received']"
          >
            {{ msg.text }}
          </div>
        </div>
        <div class="input_message">
          <el-button class="swim" :icon="Star" circle @click="showEmojiDialog = true" />
          <el-input
              v-model="message"
              size="large"
              placeholder="请在此输入内容开始聊天吧"
              @keyup.enter="sendMessage"
          />
          <el-button :icon="Promotion" circle @click="sendMessage" />
        </div>
      </div>
    </div>

    <!-- 表情弹框 -->
    <el-dialog v-model="showEmojiDialog" title="选择表情" width="30%">
      <div class="emoji-list">
        <span v-for="emoji in emojis" :key="emoji" @click="addEmoji(emoji)">
          {{ emoji }}
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { Search, Plus, Promotion, Star } from '@element-plus/icons-vue';

const search = ref("");
const message = ref("");
const selectedChat = ref(null);

// 控制表情弹框的显示与隐藏
const showEmojiDialog = ref(false);

// 组件初始化时从 localStorage 中读取聊天数据
onMounted(() => {
  const storedChatList = localStorage.getItem('chatList');
  if (storedChatList) {
    chatList.value = JSON.parse(storedChatList);
  }
});

// 默认列表-初次渲染的列表-在不做搜索时显示的列表
const chatList = ref([
  {
    username: '花心大萝卜',
    messages: [
      { id: 1, text: '你好', isSent: false },
      { id: 2, text: '你好，很高兴见到你！', isSent: true },
      { id: 3, text: '有什么可以帮助你的吗？', isSent: false },
      { id: 4, text: '我想了解一下你们的产品。', isSent: true }
    ],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  },
  {
    username: '黑心小白菜',
    messages: [],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  },
  {
    username: '滚烫蟹黄包',
    messages: [],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  },
  {
    username: '冰的咯牙糖',
    messages: [],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  },
  {
    username: '好好学习',
    messages: [],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  },
  {
    username: '天天向上',
    messages: [],
    lastMessage: '',
    time: '12:00',
    num: '99+'
  }
]);

// 表情列表
const emojis = ref([
  '😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚', '🙂', '🤗', '🤔', '😐', '😑', '😶', '🙄', '😏', '😣', '😥', '😮', '🤐', '😯', '😪', '😫', '😴', '😌', '😛', '😜', '😝', '🤤', '😒', '😓', '😔', '😕', '🙃', '🤑', '😲', '🙁', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😩', '🤯', '😬', '😰', '😱', '🥵', '🥶', '😳', '🤪', '😵', '😡', '😠', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '😇', '🤠', '🤡', '🥳', '😎', '🤓', '🧐', '🤓', '🤖', '🧟', '👀', '👁️‍🗨️', '🧠', '💪', '🦾', '🦿', '👋', '👌', '👍', '👎', '👏', '🙌', '🙏', '🤝', '✌️', '🤞', '✌️', '✍️', '💪', '💪', '💪'
]);

// 搜索功能,过滤聊天列表
const filteredChats = computed(() => {
  if (search.value.trim() === '') {
    return chatList.value;
  }
  return chatList.value.filter(chat => chat.username.includes(search.value));
});

// 选择聊天
const selectChat = (chat) => {
  selectedChat.value = chat;
  updateLastMessage(chat);
};

// 发送消息
const sendMessage = () => {
  if (message.value.trim() !== '') {
    // 更新当前选中聊天对象的消息
    selectedChat.value.messages.push({ text: message.value, isSent: true });
    // 清空输入框
    message.value = '';
    updateLastMessage(selectedChat.value);
    scrollToBottom();
    // 保存聊天数据到 localStorage
    saveChatData();
  }
};

// 保存聊天数据
const saveChatData = () => {
  localStorage.setItem('chatList', JSON.stringify(chatList.value));
};

// 更新消息
const updateLastMessage = (chat) => {
  chat.lastMessage = chat.messages[chat.messages.length - 1]?.text || '';
  // 保存聊天数据到 localStorage
  saveChatData();
};

// 过滤聊天列表的方法
const filterChats = () => {
  // 触发过滤逻辑
};

// 滚动到最底部,实现每次发送消息都自动滚动显示出来
const scrollToBottom = () => {
  nextTick(() => {
    const container = ref.messageContainer;
    container.scrollTop = container.scrollHeight;
  });
};

// 添加表情
const addEmoji = (emoji) => {
  message.value += emoji;
  showEmojiDialog.value = false;
};
</script>

<style lang="less" scoped>
  // 引入样式
  @import "Message.less";
</style>
